const http = require('http');
const lark = require('@larksuiteoapi/node-sdk');

//更改对应的app_id
const FEISHU_APP_ID = "cli_a5353776bba9100d";
const FEISHU_APP_SECRET = "nSNp3X7T6NWgP7kkY3Rt9dGJpfjBbPcR";

const client = new lark.Client({
    appId: FEISHU_APP_ID,
    appSecret: FEISHU_APP_SECRET
});

const eventDispatcher = new lark.EventDispatcher({
    verificationToken: 'Sj3iYPZCxF2E0mLtjsO5VfMytYhSoLik'
}).register({
    'im.message.receive_v1': async (data) => {
        console.log("im.message.receive_v1");
        console.log(data);
        const {message: {content, chat_id}} = data;
        const msg = JSON.parse(content).text;
        await client.im.message.createByCard({
            params: {
                receive_id_type: "chat_id"
            },
            data: {
                receive_id: chat_id,
                template_id: 'ctp_AAiWZwt1wsse'
            }
        });
    }
});

const messageCardHandler = new lark.CardActionHandler({
    verificationToken: 'Sj3iYPZCxF2E0mLtjsO5VfMytYhSoLik'
}, async (data) => {
    const {
        open_id,
        token,
        action: {
            value: {
                option
            }
        }
    } = data;

    console.log(data)


    return 'success';
});

const pickRequestData = (req) => new Promise((resolve) => {
    let chunks = '';
    req.on('data', (chunk) => {
        chunks += chunk;
    });

    req.on('end', () => {
        const data = JSON.parse(chunks);
        resolve(data);
    });
});

const SERVER_PORT = 8899;
const server = http.createServer();
server.on('request', lark.adaptDefault('/webhook/event', eventDispatcher, {autoChallenge: true}));
server.on('request', lark.adaptDefault('/webhook/message-card', messageCardHandler, {autoChallenge: true}));
// server.on('request', async (req, res) => {
//     console.log('请求方式-----------：', req.method + " -- start");
//     console.log(req.headers['host']);
//     if (req.method === 'POST') {
//         const data = (await pickRequestData(req));
//         console.log(data);
//     }
//
//     res.end(JSON.stringify({method: `${req.method}`, code: 1, msg: 'Success'}))
// });
server.listen(SERVER_PORT);
console.log(`服务启动成功，端口${SERVER_PORT}`);